package com.jourwon.spring.boot.config;

import com.jourwon.spring.boot.prop.Pf4jProperties;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.pf4j.AbstractPluginManager;
import org.pf4j.spring.SpringPluginManager;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.io.IOException;
import java.nio.file.Paths;

/**
 * Spring 配置类
 *
 * @author JourWon
 * @date 2021/9/14
 */
@Slf4j
@Configuration
@EnableConfigurationProperties(Pf4jProperties.class)
public class SpringPluginManagerConfig {

    @Bean
    public SpringPluginManager springPluginManager(Pf4jProperties prop) {
        String mode = prop.getMode();
        String pluginsDir = prop.getPluginsDir();
        System.setProperty(AbstractPluginManager.MODE_PROPERTY_NAME, mode);
        System.setProperty(AbstractPluginManager.PLUGINS_DIR_PROPERTY_NAME, pluginsDir);
        log.info("插件运行模式:{},插件目录:{}", mode, pluginsDir);
        try {
            FileUtils.forceMkdir(FileUtils.getFile(new String[]{pluginsDir}));
            log.info("强制创建插件目录成功:{}", pluginsDir);
        } catch (IOException e) {
            log.error("the directory:{} cannot be created,{}", pluginsDir, e.getMessage(), e);
        }
        return new SpringPluginManager(Paths.get(pluginsDir));
    }

    // @Bean
    // public SpringPluginManager pluginManager() {
    //     return new SpringPluginManager();
    // }

}
